package com.sywb.chuangyebao.view;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.MyApplication;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.MessageNum;
import com.sywb.chuangyebao.contract.MainContract;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.Utils;
import com.sywb.chuangyebao.view.dialog.MainPublishDialog;
import com.sywb.chuangyebao.view.fragment.CywlxFragment;
import com.sywb.chuangyebao.view.fragment.FindProjectFragment;
import com.sywb.chuangyebao.view.fragment.HomeFragment;
import com.sywb.chuangyebao.view.fragment.QAndAFragment;
import com.sywb.chuangyebao.view.fragment.UserFragment;
import com.sywb.chuangyebao.view.fragment.WebFragment;

import org.bining.footstone.adapter.BasePagerFragmentAdapter;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.utils.SharedUtils;
import org.bining.footstone.utils.ToastUtils;
import org.bining.footstone.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 主页
 */
public class MainAtlasActivity extends ActionbarActivity<MainContract.Presenter> implements MainContract.View {

    @BindView(R.id.main_content)
    NoScrollViewPager mainContent;
    @BindView(R.id.main_home_icon)
    ImageView mainHomeIcon;
    @BindView(R.id.main_home_text)
    TextView mainHomeText;
    @BindView(R.id.main_home)
    RelativeLayout mainHome;
    @BindView(R.id.main_ask_icon)
    ImageView mainAskIcon;
    @BindView(R.id.main_ask_text)
    TextView mainAskText;
    @BindView(R.id.main_ask)
    RelativeLayout mainAsk;

    @BindView(R.id.main_go_icon)
    ImageView mainGoIcon;
    @BindView(R.id.main_go_text)
    TextView mainGoText;
    @BindView(R.id.main_go)
    RelativeLayout mainGo;

    @BindView(R.id.main_service_icon)
    ImageView mainServiceIcon;
    @BindView(R.id.main_service_text)
    TextView mainServiceText;
    @BindView(R.id.main_service)
    RelativeLayout mainService;
    @BindView(R.id.main_user_icon)
    ImageView mainUserIcon;
    @BindView(R.id.main_user_unread)
    ImageView mainUserUnread;
    @BindView(R.id.main_user_layout)
    RelativeLayout mainUserLayout;
    @BindView(R.id.main_user_text)
    TextView mainUserText;
    @BindView(R.id.main_user)
    RelativeLayout mainUser;


    @BindView(R.id.main_line)
    View mainLine;
    @BindView(R.id.main_tab)
    LinearLayout mainTab;

    private int currentItem;
    private int selectIndex = -1;

    private boolean isFullScreen;//是否处于全屏状态

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        currentItem = intent.getIntExtra("p0", 0);
//    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_main_atlas;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        if (savedInstanceState == null) {
            currentItem = getIntent().getIntExtra("p0", 0);
        } else {
            currentItem = savedInstanceState.getInt("p0", 0);
        }

        ((MyApplication) getApplication()).getAppComponent().appManager().exitOtherActivity(this);

//        ((MyApplication) getApplication()).getAppComponent().appManager().killActivity(SplashActivity.class);
//        ((MyApplication) getApplication()).getAppComponent().appManager().killActivity(GuideActivity.class);

        initData();
    }

    /**
     * 初始化数据
     */
    public void initData() {
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(HomeFragment.newInstance());
        fragmentList.add(QAndAFragment.newInstance());
//        fragmentList.add(CywlxFragment.newInstance());
//        fragmentList.add(WebFragment.newInstance(1, "http://m.3158.cn/xiangmu/?site=cybxm-android"));
        fragmentList.add(FindProjectFragment.newInstance());
        fragmentList.add(UserFragment.newInstance());
        BasePagerFragmentAdapter fragmentAdapter = new BasePagerFragmentAdapter(getSupportFragmentManager(), fragmentList);
        mainContent.setAdapter(fragmentAdapter);
        mainContent.setOffscreenPageLimit(4);
        mainContent.setCurrentItem(currentItem);
        changeFooterState(currentItem);
    }

    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
        insertScreenAD();
    }

    /**
     * 获取首页插屏广告
     */
    public void insertScreenAD() {
        HttpUtils.insertScreenAD(new HttpCallback<String>() {
            @Override
            public void onSuccess(String s) {
                if (!TextUtils.isEmpty(s)) {
                    HashMap<String, String> contactusMap = JSON.parseObject(s, new TypeReference<HashMap<String, String>>() {
                    });
                    if (contactusMap != null && contactusMap.containsKey("url")) {
                        Intent intent = new Intent(mContext, InterstitialActivity.class);
                        intent.putExtra("p0", contactusMap.get("url"));
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("p0", selectIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View view) {
        if (!isCanClick(view)) return;
        switch (view.getId()) {
            case R.id.main_home:
                changeFooterState(0);
                break;
            case R.id.main_ask:
                changeFooterState(1);
                break;
//            case R.id.main_go:
//                changeFooterState(2);
//                break;
            case R.id.main_service:
//                changeFooterState(3);
                changeFooterState(2);
                break;
            case R.id.main_user:
//                changeFooterState(4);
                changeFooterState(3);
                break;
            case R.id.main_publish:
                if (Utils.checkIsNext(getMyFragmentManager())) {
                    MainPublishDialog.newInstance().show(getMyFragmentManager(), "publishDialog");
                }
//                pushData();
                break;
        }
    }

    public void pushData() {
        HttpUtils.pushData(new HttpCallback<String>() {
            @Override
            public void onSuccess(String s) {
                ToastUtils.show(mContext, "发送成功");
            }

            @Override
            public void onError(String strMsg) {
                super.onError(strMsg);
                ToastUtils.show(mContext, strMsg);
            }
        });
    }

//    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.USERISLOGIN)})
//    public void rxIsLogin(String isLogin) {
//        Logger.e("收到登录状态改变广播：" + isLogin);
//        if (SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
//            changeFooterState(4);
//        } else {
//            changeFooterState(0);
//        }
//    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.POST_LIST_CATEGORY)})
    public void rxBack(String data) {
        Logger.e("切换分类.Main：" + data);
        changeFooterState(1);
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.TOPIC_TYPE_USER)})
    public void goTutor(String data) {
        Logger.e("HOME 跳到 导师 界面");
        //跳到 导师 界面
        changeFooterState(0);
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.USERISLOGIN)})
    public void rxIsLogin(String isLogin) {
        Logger.e("收到登录状态改变广播：" + isLogin);
        if (!SharedUtils.getBoolean(Constants.USERISLOGIN, false)) {
            setMesssageUnread(null);
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.POST_MY_MSGNUM)})
    public void rxMsgNumChnage(String data) {
        setMesssageUnread(data);
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.HOMETABCHANGE)})
    public void rxTabShow(String data) {
        if (data.equals("商城")) {
            mainLine.setVisibility(View.GONE);
            mainTab.setVisibility(View.GONE);
        } else {
            mainLine.setVisibility(View.VISIBLE);
            mainTab.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.ISFULLSCREEN)})
    public void rxIsFullScreen(String data) {
        Logger.e("rxIsFullScreen:" + data);
        isFullScreen = (Integer.valueOf(data) == Configuration.ORIENTATION_LANDSCAPE);
    }

    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.USERMESSAGERECEIVER)})
    public void rxChangeToBusinessTV(String data) {
        Logger.e("收到消息通知被点击事件 rxChangeToBusinessTV");
        if (mPresenter != null) {
            mPresenter.aliViewJump();
        }
    }

    public void setMesssageUnread(String messageNumJson) {
        if (!TextUtils.isEmpty(messageNumJson)) {
            MessageNum messageNum = JSON.parseObject(messageNumJson, MessageNum.class);
            if (messageNum.notify_num > 0 || messageNum.msg_num > 0 || messageNum.note_num > 0) {
                mainUserUnread.setVisibility(View.VISIBLE);
            } else {
                mainUserUnread.setVisibility(View.INVISIBLE);
            }
        } else {
            mainUserUnread.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 改变选项卡状态
     */
    private void changeFooterState(int position) {
        if (position == selectIndex) {
            return;
        }

        switch (position) {
            case 0:
                mainHomeIcon.setSelected(true);
                mainHomeText.setSelected(true);
                break;
            case 1:
                mainAskIcon.setSelected(true);
                mainAskText.setSelected(true);
                break;
            case 2:
//                mainGoIcon.setSelected(true);
//                mainGoText.setSelected(true);
//                break;
//            case 3:
                mainServiceIcon.setSelected(true);
                mainServiceText.setSelected(true);
                break;
            case 3:
//            case 4:
                mainUserIcon.setSelected(true);
                mainUserText.setSelected(true);
                break;
        }

        switch (selectIndex) {
            case 0:
                mainHomeIcon.setSelected(false);
                mainHomeText.setSelected(false);
                break;
            case 1:
                mainAskIcon.setSelected(false);
                mainAskText.setSelected(false);
                break;
            case 2:
//                mainGoIcon.setSelected(false);
//                mainGoText.setSelected(false);
//                break;
//            case 3:
                mainServiceIcon.setSelected(false);
                mainServiceText.setSelected(false);
                break;
            case 3:
//            case 4:
                mainUserIcon.setSelected(false);
                mainUserText.setSelected(false);
                break;
        }

        mainContent.setCurrentItem(position, false);
        selectIndex = position;

        RxBus.get().post(Constants.MAINTABCHANGE, String.valueOf(selectIndex));
    }

    @Override
    public void hasNews(boolean isNews) {
        mainUserUnread.setVisibility(isNews ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPresenter.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPresenter.aliViewJump();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        exit();
    }

    @Override
    public void exit() {
        if (isFullScreen) {
            isFullScreen = false;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            return;
        }
        long newClickTime = System.currentTimeMillis();
        if (newClickTime - oldClickTime < 1000) {
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            intent.addCategory(Intent.CATEGORY_HOME);
//            startActivity(intent);
//            if (!isTaskRoot()) {
//                finish();
//            }
            moveTaskToBack(false);

            // ((MyApplication) getApplication()).getAppComponent().appManager().appExit();
        } else {
            oldClickTime = newClickTime;
            ToastUtils.show(mActivity, R.string.app_exit);
        }
    }

    @Override
    public boolean useFragment() {
        return false;
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    @Override
    public boolean useSwipeFinish() {
        return false;
    }
}
